<template>
    <ul class="list">
        <li class="item" v-for ='item of letters' :key='item' :ref ='item'
        @touchstart ='handleTouchStart'
        @touchmove ='handleTouchMove'
        @touchend ='handleTouchEnd'
        @click ='handleLetterClick'
        >{{item}}</li>
    </ul>
</template>
<script>
export default {
    name:'CityAlphabet',
    props:{
        cities:Object
    },
    // 定义一个空数组
    computed: {
        letters (){
            const letters = []
            for(let i in this.cities){
                letters.push(i)
            }
            return letters
        }
    },
    data(){
        return {
            touchStatus:false,
            startY:0,
            timer:null
        }
    },
    updataed (){//为了startY的性能
        this.startY = this.$refs['A'][0].offsetTop
    },
    methods:{
        handleLetterClick (e){
            //将点击的内容传递给父组件
            this.$emit('change',e.target.innerText)
        },
        // 为了实现滚动到哪里，字母有变化的效果
        handleTouchStart(){
            this.touchStatus= true
        },
        handleTouchMove(e){
            if(this.touchStatus) {
                // 为了优化拖锥的效果,的函数截留
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout (()=>{//
                // 表示是拖到那个字母到顶部的距离
                const startY= this.$refs['A'][0].offsetTop
                // 表示A字母到蓝色区域的距离
                const touchY = e.touches[0].clientY - 84
                // 到的A字母到C字母的下标
                const index = Math.floor((touchY-this.startY)/22)-3
                // 再触发change事件
                if(index >= 0 && index < this.letters.length){
                    this.$emit('change',this.letters[index])
                }  
                },16)
            }
        },
        handleTouchEnd(){
            this.touchStatus= false
        }
    }
}
</script>
<style lang = 'stylus' scoped>
 @import '~style/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgcolor
</style>

